package com.jec.module;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.jec.Bootstrap;
import com.jec.utils.Response;

import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping(value = "/portdisabled")
@Log4j
public class PortDisabledController {
	
	private List<String> diabledPorts = Lists.newLinkedList();
	
    @PostConstruct
    public void init(){
    	
		File configFile = getConfigFile();
		
		log.info("Loading: " + configFile.getAbsolutePath());
		
		if(configFile.exists() && configFile.isFile()) {
			
			try(FileReader fr = new FileReader(configFile)) {
				
				BufferedReader br = new BufferedReader(fr);
				
				String str;
				while ((str = br.readLine()) != null) {
					
					String entry = str.trim();
					if(!entry.isEmpty())
						diabledPorts.add(entry);

				}
				
				br.close();

			} catch(Exception e) {
				log.warn("Load names failed.", e);
			}
		}
		
    }

	
	private File getConfigFile() {
		
		String path = Bootstrap.getApplicationPath();
		
		String filename = path + File.separatorChar + "disabledports.txt";
		
		File configFile = new File(filename);
		
		return configFile;
	}
	
	
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody
    Response index(){
        return Response.Builder(diabledPorts);
    }
    
    @RequestMapping(value = "add/{entry}", method = RequestMethod.GET)
    public @ResponseBody
    Response add(@PathVariable(value = "entry") String entry){
    	
    	log.info("Add disabled port: " + entry);
    	
    	diabledPorts.add(entry);

        return Response.Builder();
    }
	
}
